﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using NRemedy;
using BMC.ARSystem;
using System.Windows.Forms;
using NRemedy.CodeGenerate;

namespace Wicresoft.NRemedy.VS10Addin.UI
{
    public class FieldLoader
    {
        public event SendPropertyListDelegation OnLoadCompeleted;

        private string _server;
        private string _user;
        private string _password;
        private string _formname;

        public FieldLoader()
        {
        }

        //这个函数在UI线程中执行 
        public void LoadProperties(string server,string user,string password,string formname)
        {
            _server = server;
            _user = user;
            _password = password;
            _formname = formname;
            Thread thread = new Thread(new ThreadStart(LoadInternal));
            thread.Start();
        }
        //这个函数在新的线程中执行 
        private void LoadInternal()
        {
            List<ModelPropertyInfo> rdata = new List<ModelPropertyInfo>();

            using (ARLoginContext context = new ARLoginContext(_server, _user, _password))
            {
                ARSchema arschema = new ARSchema(context);
                IGetARFieldFilterDelegate affd = new CSharpModelGeneratorDefaultFactory().CreateGetARFieldFilterDelegate();
                var fields = arschema.GetListField(_formname, affd.getARFieldFilterDelegate());
                foreach (Field f in fields)
                {
                    ModelPropertyInfo mpi = new ModelPropertyInfo();
                    mpi.RemedyFieldId = f.FieldId.ToString();
                    mpi.RemedyFieldName = f.Name;
                    mpi.ModelPropertyName = f.GetType().Name;
                    rdata.Add(mpi);
                }
            }

            if (OnLoadCompeleted != null)
            {
                //获取myDelegate的目标对象，这里将是Form1的实例 
                Control control = OnLoadCompeleted.Target as Control;
                //如果目标对象是个Control的话 
                if (control != null)
                {
                    //通过调用form的invoke，把委托指向的函数NotifyReceiver送到UI线程上执行 
                    control.Invoke(OnLoadCompeleted, rdata);
                }
                //如果目标对象不是Control，则直接执行委托 
                else
                {
                    OnLoadCompeleted(rdata);
                }
            } 

        } 
    }
}
